package com.sentrix.auto.printercenter.domain.entity;

import com.mybatisflex.annotation.Table;
import com.sentrix.auto.printercenter.domain.event.AgentStatusChangedEvent;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.List;

@EqualsAndHashCode(callSuper = true)
@Data
@Table(value = "agent")
public class PrinterAgentEntity extends BaseEntity {
    private String code;
    private String name;
    private Boolean isOnline;
    private Long gmtConnect;
    private Long gmtDisconnect;
    private String sessionId;

    private List<PrinterEntity> printers;

    public void connect(String sessionId) {
        this.sessionId = sessionId;
        this.isOnline = Boolean.TRUE;
        this.gmtConnect = System.currentTimeMillis();
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            @Override
            public void beforeCommit(boolean readOnly) {
                publishStatusChangedEvent();
            }
        });
    }

    public void disconnect() {
        this.sessionId = null;
        this.isOnline = Boolean.FALSE;
        this.gmtDisconnect = System.currentTimeMillis();
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            @Override
            public void beforeCommit(boolean readOnly) {
                publishStatusChangedEvent();
            }
        });
    }

    // 发布领域事件（由领域事件总线处理）
    private void publishStatusChangedEvent() {
        AgentStatusChangedEvent.publish(this.code, this.isOnline, this.gmtConnect, this.gmtDisconnect);
    }
}
